<template>
  <div>
    <div class="block">
      <span class="demonstration" style="margin-right: 10px">项目选择</span>
      <el-cascader
          v-model="value"
          :options="options"
          :props="{ expandTrigger: 'hover' }"
          @change="handleChange"
      >
      </el-cascader>
      <el-button style="float: right" @click="playBack">查看员工轨迹</el-button>
    </div>
    <el-row :gutter="20">
      <el-col :span="16">
        <div style="height: 560px;overflow: hidden">
          <div id="container" style="width: 100%;height: 700px;margin-top: 20px"></div>
        </div>
      </el-col>
<!--      员工信息-->
      <el-col :span="8">
        <div class="users" style="height: 30vh;width:100%;margin-top: -10px"><br>
          <el-card :body-style="{ padding: '10px'}"
                   :style="{ borderRadius: '15px' ,boxShadow: '0 0 20px rgba(0, 0, 0, 0.3)'}">

            <div style="color:#0c1c39;text-align: center;font-weight: bold;font-size: larger;">
             员工信息</div>
              <div class="demo-type" style="float: left;width: 80px;height: 15vh;margin-top: 35px;margin-left: 5px">
                <el-avatar @error="errorHandler" shape="square" :size="80">
                  <img class="el-avatar--icon" v-if="user.avatar" :src="'http://localhost:8080/'+user.avatar"
                       style="width: 100%;"/>
                </el-avatar>
              </div>
            <div v-if="user" style="padding: 15px;margin-left:90px;overflow-wrap: break-word;">
              <span>设备：{{ user.deviceId }}</span><br>
              <span>姓名：{{ user.username }}</span><br>
              <span>电话：{{ user.phonenumber }}</span><br>
              <span>职责：{{ role.name }}</span><br>
              <span>所在省份：{{ dept.province }}</span><br>
              <span >所在工程：{{ dept.name }}</span><br>
            </div>
          </el-card>
        </div>
      </el-col>

      <el-col :span="8">
        <div class="grid-content" style="margin-top: 20px;">
          <div class="chat-container" >
            <el-row>
              <el-col :span="10">
                <div class="chat-messages" style="display: inline-block;">
                  <div style="display: inline-block">
                    <div class="demo-type" style="width: 80px;margin-left: 5px;margin-top: 20px;display: inline-block">
                      <el-avatar @error="errorHandler" shape="circle" :size="40">
                        <img class="el-avatar--icon" v-if="user.avatar" :src="'http://localhost:8080/'+user.avatar"
                             style="width: 100%;"/>
                      </el-avatar>
                    </div>
                      <div style="color: #4c4b4e;margin-left: -30px;width: 80px;height:20px;display: inline-block" class="chat-name">
                        {{ this.user.username }}
                    </div>
                    <div style="clear: both"></div>
                  </div>
                </div>
                <div class="chat-input">
                  <div style="margin-top: 30px" class="chat-text">{{ constantData.text }}</div>
                  <div style=" color: #c8c7cc;font-size: smaller" class="chat-time">{{ constantData.time }}</div>
                  <el-input v-model="newMessage" placeholder="请输入消息..."/>
                  <el-button style="width: 100%;margin-top: 20px" type="primary" @click="sendMessage">发送</el-button>
                </div>
              </el-col>
              <el-col :span="12" >
                <div style="margin-top: 20px">
                  <el-select v-if="selectUser.length>0" v-model="selectInfo" @change="selectUsers" placeholder="请选择区域外员工"
                  style="border: 1px solid #536eae; border-radius: 4px;width: 200px;margin-left: 40px"
                  >
                    <el-option
                        v-for="item in selectUser"
                        :key="item"
                        :label="item"
                        :value="item"
                       >
                    </el-option>
                  </el-select>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import request from "@/utils/request";
import esrequst from "@/utils/esrequst";

export default {
  data() {
    return {
      warMsg: {
        senderId: 1,
        receiverId: 0,
        content: "",
      },
      constantData: {},
      //当前用户头像
      thisAvatar: "",
      //发送消息的目标，如果为 “” 表示全部
      toUser: "",
      //websocket 对象
      ws: null,
      // 聊天消息数据...
      messages: [],
      //输入框里面的内容
      newMessage: '',
      onlineUsers: [],
      users: {},
      role: {},
      dept: {},
      positions: [],
      //设备ID集合
      anchor: [],
      //经纬度集合
      lnglats: [],
      //用户信息
      user: {},
      //项目选择下拉树
      options: [],
      value: [],
      map: {},
      circle: {},
      path:[],
      //省份
      position: '',
      //关闭定时器
      timer: "",
      //这是存放用户设备编号和roleKey的map
      mapData: null,
      markers: [],
      //电子围栏外部信息
      selectUser:[],
      selectInfo:"",
      hatMap: [],
    }
  },
  watch: {

    //监听设备ID集合变化
    anchor() {
      // this.markers.forEach(o => {
      //   console.info(o)
      //   this.map.remove(o);
      // });
       this.map.remove(this.markers);
      this.markers = [];
      this.selectUser=[]
      for (var i = 0; i < this.lnglats.length; i++) {
        var lnglat = this.lnglats[i];
        // 创建点实例

        let imgPath
        if (this.mapData.get(this.anchor[i]) != undefined) {
          imgPath = require("@/assets/" + this.mapData.get(this.anchor[i]) + ".png")
        } else {
          imgPath = require("@/assets/worker.png")
        }
        var marker = new AMap.Marker({
          position: new AMap.LngLat(lnglat[0], lnglat[1]),
          content: `<div class="custom-content-marker">${this.anchor[i]}<img src=${imgPath} height="40px" width="40px"></div>`,
          anchor: "center",
          // 以 icon 的 [center bottom] 为原点
          offset: new AMap.Pixel(-13, -30),
          extData: {
            id: i + 1
          }
        });

        if (this.path.length > 0) {
          var isPointInRing = AMap.GeometryUtil.isPointInRing(lnglat, this.path);
          //this.anchor[i]电子围栏外部数据
          if (this.mapData.get(this.anchor[i]) != undefined && !isPointInRing) {
            this.selectUser.push(this.anchor[i])
            console.log(this.anchor[i])
          }
          marker.setLabel({
            content: isPointInRing ? '内部' : '外部',
            offset: new AMap.Pixel(20, 0)
          });
        }
        marker.on('click', this.showInfo);
        this.markers.push(marker);
      }
      // 将点添加到地图
      this.map.add(this.markers);
    }
  },
  async mounted() {
    // console.info(123 + this.anchor)
    //创建地图
    this.map = new AMap.Map("container", {
      zoom: 13,
      center: [106.678902, 26.509553],
      resizeEnable: true
    });

    //查询所有用户
    let userList = await request("user")
    //将用户的设备编号作为键，roleKey作为值，用来设置每个角色的帽子
    let map = new Map()
    userList.forEach(u => {
      if (u.role) {
        map.set(u.deviceId, u.role.roleKey)
      }
    })
    this.mapData = map
    //查询部门
    let dept = await request("dept")
    this.options = this.transformedData(dept)
    this.refreshMap()
    this.timer = setInterval(() => {
      this.refreshMap()
    }, 10000)
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    playBack(){
      if (this.user.deviceId){
        let time=this.hatMap.get(this.user.deviceId)
        // 将字符串解析为Date对象
        const date = new Date(time);
// 使用getFullYear(), getMonth(), getDate()方法提取年、月、日部分
        const year = date.getFullYear();
        let month = date.getMonth() + 1;
        const day = date.getDate();
// // 月份需要补零
       let month1 = month < 10 ? '0' + month : month;
// 组合成目标格式的字符串
        const formattedDate = `${year}-${month1}-${day}`;
        this.$router.push(`/index/playbackPage?userId=${this.user.deviceId}&date=${formattedDate}`)
      }else {
        this.$message.error("请选择员工")
      }
      console.info( this.user)
    },

    selectUsers(id){
      this.showInfo(id)
    },
    async refreshMap() {
      let data = await esrequst("gyhat02/_search", "POST",
          {
            "size": 0,
            "aggs": {
              "user_ids": {
                "terms": {
                  "field": "userId.keyword",
                  "size": 30,
                },
                "aggs": {
                  "latest_hit": {
                    "top_hits": {
                      "size": 1,
                      "sort": [
                        {
                          "date": {
                            "order": "desc"
                          }
                        }]
                    }
                  }
                }
              }
            }
          })
      this.lnglats = []
      this.anchor = []
      let map = new Map()
      data.aggregations.user_ids.buckets.forEach(async d => {
        map.set(d.latest_hit.hits.hits[0]._source.userId, d.latest_hit.hits.hits[0]._source.date)
        this.lnglats.push([Number(d.latest_hit.hits.hits[0]._source.longitude), Number(d.latest_hit.hits.hits[0]._source.latitude)])
        this.anchor.push(d.key)
      })
      this.hatMap = map

    },
    //将部门集合转为树形选项
    transformedData(yourData) {
      console.info(yourData)
      // 根据province分组数据
      const groupedData = yourData.reduce((acc, item) => {
        if (!acc[item.province]) {
          acc[item.province] = [];
        }
        acc[item.province].push({value: item.id, label: item.name});
        return acc;
      }, {});

      // 转换成指定格式的数组
      const result = Object.keys(groupedData).map(key => {
        return {
          value: key,
          label: key,
          children: groupedData[key]
        };
      });

      return result;
    },
    //项目选择变化,绘制电子围栏
    async handleChange(value) {

      if (this.circle != null) {
        this.map.remove(this.circle);
      }
      if (value[1]) {
        this.position = value[1]
      }

      this.path = []
      let data = await request("project?deptId=" + this.position)
      data = data.sort((a, b) => a.sort - b.sort);

      data.forEach(o => {
        this.path.push([o.longitude, o.latitude])
      })

      this.circle = new AMap.Polygon({
        path: this.path,
        strokeColor: "#FF33FF",
        strokeWeight: 6,
        strokeOpacity: 0.2,
        fillOpacity: 0.4,
        fillColor: '#1791fc',
        zIndex: 50,
        bubble: true,
      })

      this.map.add(this.circle);
      // 缩放地图到合适的视野级别
      this.map.setFitView([this.circle])
    },
    async showInfo(e) {
      this.user = {}
      this.role = {}
      this.dept = {}
      let target
      if (this.selectInfo){
        target=e
      }else{
        target=e.target.dom.outerText.substring(0, 4)
      }
      let data = await request("/user?deviceId=" + target)
      if (data.length > 0) {
        this.user = data[0];
        this.role = data[0].role
        this.dept = data[0].dept
      }
      this.constantData = {}
      this.ws = new WebSocket("ws://localhost:8080/ws/" + this.user.deviceId);

      this.selectInfo=''
// 监听WebSocket事件
      this.ws.onopen = function () {
        console.log('WebSocket连接已建立');
      };

      this.ws.onmessage = function (event) {
        console.log('接收到数据：' + event.data);
        // 在这里处理接收到的数据
      };

      this.ws.onerror = function (event) {
        console.error('WebSocket发生错误：' + event);
      };

      this.ws.onclose = function () {
        console.log('WebSocket连接已关闭');
      };

    },
    sendMessage() {
      if (this.newMessage.trim() !== '') {
        const newId = this.messages.length + 1;
        const currentTime = new Date().toLocaleTimeString('en-US', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        }).replace(/(\d+)\/(\d+)\/(\d+), /, '$3-$1-$2 ');
        const newMessage = {
          id: newId,
          type: "MESSAGE",
          toUser: this.user.deviceId,
          name: this.user.username,
          text: this.newMessage,
          time: currentTime,
          avatar: this.user.avatar,
        };
        this.constantData = newMessage;

        this.ws.send(JSON.stringify(newMessage))
        this.warMsg.receiverId = this.user.userId
        this.warMsg.content = this.newMessage
        request("warningMessage", "post", this.warMsg)

        this.newMessage = ''
      }
    },
    async insertMap() {
      /*let data = await request("city")
      data.forEach(o => {
        this.options.push({
          value: o.id,
          label: o.provinceName,
        })
      })*/
    },
    errorHandler() {
      return true
    },
  }

}
</script>
<style scoped>
.grid-content {
  height: 40vh;
}

.users {
  height: 40vh;
  margin-bottom: 10px;
}
</style>
